#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"


int getword(node_st **ptr,FILE *fps)
{
	ssize_t i,len,k = 0;
	char key[KEYSIZE] = {0};
	char *buff = NULL;
	int pos = 0;
	size_t line = 0;
	len = getline(&buff,&line,fps);
	if(len <= 0)
	{
		return 0;
	}
	for(i = 0;i < len && buff[i] != '\n';i++)
	{
		if(buff[i] == ' ')
		{
			key[k] = '\0';
			insert(ptr,key+pos);
			pos = strlen(key);
			continue;
		}
		if(buff[i] >= 'a' && buff[i] <= 'z')
			key[k++] = buff[i];
		if(buff[i] >= 'A' && buff[i] <= 'Z')
		{
			key[k++] = buff[i]+'a'-'A';
		}
	}
	return 1;
}



int insert(node_st **ptr,char *key)
{
	if(*ptr == NULL)
	{
		node_st *newnode = NULL;
		newnode = malloc(sizeof(node_st));
		if(newnode == NULL)
		{
			fprintf(stdout,"malloc fail\n");
			exit(1);
		}
		for(int i = 0;i < ARRSIZE;i++)
			newnode->arr[i] = NULL;
		newnode->count = 0;
		*ptr = newnode;
	}
	if(*key == '\0')
	{
		(*ptr)->count++;
		return 0;
	}
	insert((*ptr)->arr + *key - 'a',key + 1);
}

int find(node_st *ptr,char *key)
{
	if(ptr == NULL)
		return -1;
	if(*key == '\0')
	{
		return ptr->count;
	}
	find(ptr->arr[*key-'a'],key+1);	
}


void func(node_st **ptr,FILE *fps)
{
	while(getword(ptr,fps));
}

